﻿#include "BTEServer.h"
#include <QtWidgets/QApplication>
#include "CoreDump.h"
#include "LogManager.h"
#include "Security\SecurityDLL.h"
#include "SecurityClient.h"

static BTEServer *g_server = NULL;
QtMessageHandler qtLogHandler = NULL;

void exception_exit()
{
	LogManager::instance()->deinit();
	g_server->CrashExit();
	QMessageBox::information(NULL, "", qApp->translate("main", "程序异常，请联系工程师"));
}

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{		
	switch (type) {
	case QtDebugMsg:	
	case QtInfoMsg:			
	case QtWarningMsg:				
	case QtCriticalMsg:		
		qtLogHandler(type, context, msg);
		break;
	case QtFatalMsg:
		LogFatal("%s",qUtf8Printable(msg));
		RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
		break;
	}
}

void parseDataTest();

namespace JQFoundation
{
    bool singleApplication(const QString &flag)
    {
        static QSharedMemory *shareMem = nullptr;

        if (shareMem)
        {
            return true;
        }

        shareMem = new QSharedMemory("JQFoundationSingleApplication_" + flag);

        for (auto count = 0; count < 2; ++count)
        {
            if (shareMem->attach(QSharedMemory::ReadOnly))
            {
                shareMem->detach();
            }
        }

        if (shareMem->create(1))
        {
            return true;
        }

        return false;
    }
}

QTranslator *qTranslator;
void switchAppLang(int lang)
{
    QString str = QApplication::applicationDirPath() + "/lang/bteserver_en.qm";
    qApp->removeTranslator(qTranslator);
    if (lang == 1)
    {
        if (qTranslator->load(str))
            qApp->installTranslator(qTranslator);
    }
}

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
    qTranslator = new QTranslator(&a);
    
	CoreDump::init();
	CoreDump::setCallBack(exception_exit);
	qtLogHandler = qInstallMessageHandler(myMessageOutput);

    QSettings set(qApp->applicationDirPath() + "/option.ini", QSettings::IniFormat);
    int lang = set.value("lang", 0).toInt();
    if (lang == 1)
    {
        switchAppLang(lang);
    }

	//注册数据包
	NetPackRegist();
	LogManager::instance()->init(QApplication::applicationDirPath() + "/log");
	LogManager::instance()->setLogLevel(LOG_WARNING);

    BTEServer w;        
    if (!JQFoundation::singleApplication("myApplication"))
    {
        QMessageBox::information(nullptr,"", qApp->translate("main","程序不能重复启动"));
        return 1;
    }

    InitDLL("SecurityXqm");
    int ret = -1; 

#if 1
    int day;
    ret = CheckRegTime(day);
    if (ret != SECURITY_OK)
    {     
        if (ret == SECURITY_OUTDAY)
            QMessageBox::information(NULL, "", qApp->translate("main","已过期"));

        SecurityClient w;
        if (w.exec() != SecurityClient::Accepted)
            return 1;
    }
#endif

	w.setWindowFlags(Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);
	w.showMaximized();
    w.show();
	g_server = &w;

	return a.exec();
}
